package cn.tedu.travelsystem.user.controller;

import cn.tedu.travelsystem.base.response.JsonResult;
import cn.tedu.travelsystem.base.response.StatusCode;
import cn.tedu.travelsystem.base.utils.JwtUtil;
import cn.tedu.travelsystem.user.mapper.UserMapper;
import cn.tedu.travelsystem.user.pojo.dto.AdminLoginDTO;
import cn.tedu.travelsystem.user.pojo.dto.UserUpdateDTO;
import cn.tedu.travelsystem.user.pojo.entity.User;
import cn.tedu.travelsystem.user.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员模块")
public class AdminController {

    @Autowired
    private UserMapper userMapper;
    @Value("${admin.password}") // 从配置读取密码
    private String adminPassword;

    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public JsonResult login(@RequestBody AdminLoginDTO dto) {
        if (!dto.getPassword().equals(adminPassword)) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        String token = JwtUtil.generateToken("admin", Collections.singletonMap("role", "admin"));
        return JsonResult.ok(Collections.singletonMap("token", token));
    }

    @GetMapping("/users")
    @ApiOperation("获取用户列表")
    public JsonResult getUsers() {
        List<UserListVO> users = userMapper.listUser();
        return JsonResult.ok(users);
    }

    @DeleteMapping("/users/{user_id}")
    @ApiOperation("删除用户")
    public JsonResult deleteUser(@PathVariable("user_id") Long user_id) {
        userMapper.deleteUser(user_id);
        return JsonResult.ok();
    }

    @PutMapping("/users/{user_id}")
    @ApiOperation("更新用户信息")
    public JsonResult updateUser(@PathVariable("user_id") Long id, @RequestBody UserUpdateDTO userUpdateDTO) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO, user);
        user.setUser_id(id);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }
}

